from typing import List, Annotated

from fastapi import APIRouter, Depends, Query, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select

from app.db import session
from app.db.models.gallery import Gallery
from app.schemas.gallery import GalleryItem # We need to create this schema

router = APIRouter(prefix="/gallery", tags=["Gallery"])

# Define allowed categories (can be moved to config or fetched from DB)
ALLOWED_CATEGORIES = ["风景", "人物", "抽象", "其他"] # Example categories

@router.get("", response_model=List[GalleryItem])
async def browse_gallery(
    db: Annotated[AsyncSession, Depends(session.get_db)],
    category: str | None = Query(None, description=f"Filter by category. Allowed: {ALLOWED_CATEGORIES}"),
    skip: int = Query(0, ge=0),
    limit: int = Query(20, ge=1, le=100) # Smaller default limit for gallery view
):
    """Browse gallery items, optionally filtering by category."""
    if category and category not in ALLOWED_CATEGORIES:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Invalid category. Allowed categories are: {ALLOWED_CATEGORIES}"
        )

    stmt = select(Gallery).order_by(Gallery.created_at.desc())
    if category:
        stmt = stmt.filter(Gallery.category == category)
    
    stmt = stmt.offset(skip).limit(limit)
    
    result = await db.execute(stmt)
    items = result.scalars().all()
    return items

# Admin POST endpoint will be in admin.py
